package com.cangxuan.app.ui.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.*;
import android.widget.*;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Orderform;
import com.cangxuan.app.entity.Registration;
import com.cangxuan.app.ui.collection.CollectionDetailActivity;
import com.cangxuan.app.ui.collection.OrderPayActivity;
import com.cangxuan.app.ui.user.MyCollectionActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.UserUtils;

import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Author: 陈青石
 * Activity: 藏品详情（挂单） 片段
 * Layout: fragment_collectiondetail_list_bottom
 */
public class CollectionDetailListBottomFragment extends Fragment {

    public static void setListCountAndPrice(List<Registration> listTestEntities) {
        int count=0;
        int sum=0;
        for (Registration listTestEntity : listTestEntities) {
            if (listTestEntity.isChecked()){
                count++;
                sum+=listTestEntity.getPrice();
            }
        }
        goodsCount.setText("已选择"+count+"件藏品");
        goodsPrice.setText("共计:"+sum+"元");
    }

    public static int isOpen=0;
    Button submit;
    private View view;
    static TextView goodsCount;
    static TextView goodsPrice;
    Handler handler = new Handler();

    ProgressDialog progressDialog;

    Map<String,String> header;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_collectiondetail_list_bottom, container, false);
        }
        isOpen=1;

        header=new HashMap<>();
        header.put("Authorization", DeviceUtils.getDeviceID());

        goodsCount=view.findViewById(R.id.goods_count);
        goodsPrice=view.findViewById(R.id.goods_price);
        setListCountAndPrice(CollectionDetailActivity.registrations);
        submit = view.findViewById(R.id.submit);
        submit.setOnClickListener(view1 -> {
            CollectionDetailListBottomFragment.isOpen=1;
            CollectionDetailBottomFragment.dialog.dismiss();
            createRegistration(CollectionDetailActivity.registrations);

        });

        return view;
    }

    private void createRegistration(List<Registration> listTestEntities) {
        if (UserUtils.getUser(getContext())==null){
            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if(UserUtils.getUser(getContext()).isHasSetRealname()==false){
            Toast.makeText(getContext(), "请先实名认证", Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog=ProgressDialog.show(getContext(), "", "创建订单中请稍等...");

        List<Registration> sendRegistration=new ArrayList<>();
        for (Registration listTestEntity : listTestEntities) {
            if (listTestEntity.isChecked()){
                sendRegistration.add(listTestEntity);
            }
        }

        if(sendRegistration.size()==0){
            Toast.makeText(getContext(), "请选择需要购买的挂单", Toast.LENGTH_SHORT).show();
            return;
        }
        System.out.println(sendRegistration);
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(sendRegistration));
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.post("/api/registration/updateBuyerId", header,String.valueOf(array));
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONObject responseJSONObject = jsonResponse.getJSONObject("value");
                handler.post(() -> {
                    progressDialog.dismiss();
                    Intent intent = new Intent(getContext(), OrderPayActivity.class);
                    intent.putExtra("orderform", (Serializable) responseJSONObject.get("list"));
                    intent.putExtra("sum", responseJSONObject.get("sum").toString());
                    intent.putExtra("topIndex",1);
                    intent.putExtra("comeFrom",CollectionDetailActivity.comeFrom);
                    startActivity(intent);
                });
            } else {
                handler.post(() -> {
                    progressDialog.dismiss();
                    successDoChangeList();
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }



    private void successDoChangeList() {
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/registration/get/"+CollectionDetailActivity.id, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonArray = jsonResponse.getJSONArray("value");
                CollectionDetailActivity.registrations = JSONObject.parseArray(jsonArray.toJSONString(), Registration.class);
                handler.post(()->{
                    CollectionDetailBottomFragment.changeList();
                    CollectionDetailBottomFragment.setCountAndPrice(CollectionDetailActivity.registrations);
                    setListCountAndPrice(CollectionDetailActivity.registrations);
                    CollectionDetailBottomFragment.setMaxCheck();
                    progressDialog.dismiss();
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();

    }


}
